package com.example.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.entity.Modules;
import com.example.entity.TreeMenu;
import com.example.service.ModulesService;

@Controller
public class ModulesController {
	@Autowired
	private ModulesService modulesService;
	
	
	@RequestMapping("/GetSysRightsJsonLayUI")
	@ResponseBody
	public List<Modules> GetSysRightsJsonLayUI(){
		List<Modules> list=modulesService.findAllModules();
		return list;
	}
	@RequestMapping(path="/findAll")
	@ResponseBody
	public Map<String, Object> findAll(String name) {
		Map<String, Object> relMap=new HashMap<String, Object>();
		List<Modules> list=modulesService.findAll(name);
		relMap.put("code", "0");
		relMap.put("msg", "success");
		relMap.put("count", "");
		relMap.put("data", list);
		return relMap;
	}
	
	/**
	 * 查询该用户所拥有的权限的模板
	 * @param mve
	 * @return
	 */
	public List<TreeMenu> find(String roleId) {
		return modulesService.find(roleId);
	}
	/**
	* 生成模块类型树
	* @return List
	*/
	@RequestMapping("/getModule")
	@ResponseBody
	public List<TreeMenu> getModulesTreeNode(String roleId,String token) {
		List<TreeMenu> treeMenuList = this.find(roleId);
		List<TreeMenu> TreeMenus = new ArrayList<TreeMenu>();
		for (TreeMenu treeMenu : treeMenuList) {
			if (treeMenu.getParentid()==0) {
				TreeMenus.add(findChildren(treeMenu, treeMenuList));
			}
		}
		return TreeMenus;
	}
	
	/**
	* 查找子类型
	* @return List
	*/
	public TreeMenu findChildren(TreeMenu treeMenu, List<TreeMenu> treeMenuList) {
		for (TreeMenu item : treeMenuList) {
			 if (treeMenu.getId()==item.getParentid()) {
				 if(treeMenu.getChildren()==null) {
					 treeMenu.setChildren(new ArrayList<TreeMenu>());
				 } 
				 treeMenu.getChildren().add(findChildren(item,treeMenuList));
			 } 
		}
		return treeMenu;
	}
	
	/**
	 * 新增/修改
	 * @param me
	 * @return
	 */
	@RequestMapping("/module")
	@ResponseBody
	public Map<String, Object> addModules(Modules me){
		int count=0;
		if(me.getId()==0) {
			count = modulesService.addModules(me);
		}else {
			count = modulesService.upModules(me);
		}
		Map<String, Object> relMap=new HashMap<String, Object>();
		relMap.put("code", count>0?"0":"1");
		relMap.put("msg", count>0?"提交成功":"提交失败");
		return relMap;
	}

	

	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/delModules")
	@ResponseBody
	public Map<String, Object> delModules(Integer id){
		Map<String, Object> relMap=new HashMap<String, Object>();
		int count = modulesService.delModules(id);
		relMap.put("code", count>0?"0":"1");
		relMap.put("msg", count>0?"删除成功":"删除失败");
		return relMap;
	}
}
